//
//  CETradeVC.m
//  digitalCurrency
//
//  Created by 来迎宾 on 2019/4/5.
//  Copyright © 2019年 XinHuoKeJi. All rights reserved.
//

#import "CEMainTradeVC.h"
#import "CTQGListVC.h"
#import "CTProgressCell.h"
#import "CTQGHeaderView.h"
#import "MarketFooterView.h"
#import "HomeNetManager.h"

@interface CEMainTradeVC (){
    dispatch_source_t _timer;
    dispatch_source_t _timerAll;

}
@property (nonatomic, strong) CTQGHeaderView *headerView;
@property (nonatomic, strong) MarketFooterView *fview;
@property (nonatomic, copy) NSDictionary *flashSaleDic;
@property (nonatomic, strong) UILabel *canUsedCount;
@property (nonatomic, strong) UILabel *usedCount;
@property (nonatomic, strong) UILabel *percentLabel;
@property (nonatomic, strong) UILabel *qgTitle;
@property (nonatomic, assign) NSInteger daojishi;
@property (nonatomic, strong) UIView *progressView;
@property (nonatomic, strong) UIButton *issueButton;

@property (nonatomic, strong) UIView *alertView;
//@property (nonatomic, strong) NSMutableArray *lists;

@end

@implementation CEMainTradeVC
- (instancetype)init
    {
        self = [super init];
        if (self) {
            _daojishi = 0;
            //_lists = [NSMutableArray array];
        }
        return self;
    }
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = 100;
    self.tableView.separatorColor = [UIColor clearColor];
    [self.tableView registerClass:[CTProgressCell class] forCellReuseIdentifier:@"qgcell"];
    [self setTablewViewHeader];

    [self headRefreshWithScrollerView:self.tableView];
    
    [self rightButton];
    
    [self Flashsale:nil];
    
}
   
#pragma mark-下拉刷新数据
- (void)refreshHeaderAction {
    [self Flashsale:nil];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if(![YLUserInfo isLogIn]) {
        [self showLoginViewController];
    }
    else {
        self.viewTitle.text = LocalizationKey(@"Panic buying");
        [self.issueButton setTitle:LocalizationKey(@"Panic buying record") forState:UIControlStateNormal];
         
         [self Flashsale:nil];
        [self setTablewViewFooter];
        
        [self startTimerAll];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
    if (_timerAll) {
        dispatch_source_cancel(_timerAll);
    }
}
    
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    CGRect rect = self.view.bounds;
    self.tableView.frame = rect;
}

- (void)startTimer:(CGFloat)time {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateTime:_daojishi--];
        });
    });
    dispatch_resume(_timer);
}
    
- (void)startTimerAll {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timerAll = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timerAll,dispatch_walltime(NULL, 0),10.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timerAll, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self Flashsale:nil];
        });
    });
    dispatch_resume(_timerAll);
}
    
- (void)setTablewViewHeader {
    self.headerView = [[CTQGHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 320)];
    self.tableView.tableHeaderView = self.headerView;
    @weakify(self);
    [[self.headerView.qgbtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        kPreventRepeatClickTime(1);
        [self doFlashsale];
    }];
}
- (void)setTablewViewFooter {
    if (self.fview) {
        self.fview = nil;
    }
    self.fview = [[MarketFooterView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 230)];
    self.tableView.tableFooterView = self.fview;
}

- (void)RighttouchEvent {
    CTQGListVC *vc = [[CTQGListVC alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
    
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CTProgressCell *cell   = [CTProgressCell createTableView:tableView];
    self.canUsedCount = cell.canUsedCount;
    self.usedCount    = cell.usedCount;
    self.percentLabel = cell.percentLabel;
    self.progressView = cell.progressView;
    
    return cell;
}
#pragma mark - 抢购
- (void)doFlashsale {
    
    if (![self.headerView.qgTitle.text isEqualToString:LocalizationKey(@"Preemptive countdown")]) {
        [self.view makeToast:LocalizationKey(@"FlashEnd") duration:1 position:CSToastPositionCenter];
        return;
    }
    NSDictionary *dic = @{
                          @"userId":[YLUserInfo shareUserInfo].ID,
                          @"coinId":self.flashSaleDic[@"coinSymbol"]};
   
    __weak typeof(self)weakself = self;
    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    [HomeNetManager doFlashsaleInfo:dic CompleteHandle:^(id resPonseObj, int code) {
        [EasyShowLodingView hidenLoding];
        NSLog(@"抢购 ---- %@", resPonseObj);
        if (code) {
            NSInteger rescode = [resPonseObj[@"code"] integerValue];
            
            if (rescode == 0) {
                [self Flashsale:nil];
            }
            [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            
            if (rescode == -1002) {
                [self showLoginViewController];
            }
//            else if (rescode == 200) {
//                [self ViewTitleStr:@"Buy prompt" contentStr:@"您本次有500.1个待抢CT，需要5001个CT作为保证金。 您当前的保证金为0，无法参与抢购。" sureTag:100];
//            }
//            else if (rescode == 300) {
//                [self ViewTitleStr:@"Buy prompt" contentStr:@"您本次有500.1个待抢CT，需要5001个CT作为保证金。您当前的保证金为2500.5个CT，本次只能抢250.05个CT。每日只能进行一次抢购，确定现在抢购吗？" sureTag:200];
//            }
        }
        else {
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}
  
- (void)Flashsale:(NSDictionary *)dic {
    [HomeNetManager getFlashsaleBaseInfo:dic CompleteHandle:^(id resPonseObj, int code) {
        NSLog(@"抢购信息 ---- %@", resPonseObj);
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                self.flashSaleDic = resPonseObj[@"data"];
                NSTimeInterval endTime     = [self.flashSaleDic[@"endtime"] doubleValue]/1000;
                NSTimeInterval currentTime = [self.flashSaleDic[@"current_time"] doubleValue]/1000;
                NSTimeInterval startTime   = [self.flashSaleDic[@"starttime"] doubleValue]/1000;
                NSTimeInterval nextStarttime = [self.flashSaleDic[@"nextStarttime"] doubleValue]/1000;
                
                NSString *amount = [NSString stringWithFormat:@"%@",self.flashSaleDic[@"amount"]];
                if (currentTime < startTime) {
                    if (_timer) {
                        dispatch_source_cancel(_timer);
                    }
                    _daojishi = startTime - currentTime;
                    [self startTimer:_daojishi];

                    self.headerView.qgTitle.text = LocalizationKey(@"Panic buying countdown");
                    self.canUsedCount.text = [NSString stringWithFormat:@"%@:%@ DWTT",LocalizationKey(@"Current limited sale"),[ToolUtil judgeStringForDecimalPlaces:amount point:4]];
                    self.usedCount.text    = [NSString stringWithFormat:@"%@:0 DWTT",LocalizationKey(@"Rushtobuy")];
                    self.percentLabel.text = [NSString stringWithFormat:@"%@%@",LocalizationKey(@"Current buying progress"),@"0.00%"];
                    self.progressView.backgroundColor = [UIColor colorWithHEX:@"c5c5c5"];
                    
                    [self.headerView.qgbtn setImage:[UIImage imageNamed:@"qb_qianggou_end"] forState:UIControlStateNormal];
                }
                else if (currentTime < endTime) {
                    if (_timer) {
                        dispatch_source_cancel(_timer);
                    }
                    _daojishi = endTime - currentTime;
                    [self startTimer:_daojishi];
                    
                    self.headerView.qgTitle.text = LocalizationKey(@"Preemptive countdown");
                    self.canUsedCount.text = [NSString stringWithFormat:@"%@:%@ DWTT",LocalizationKey(@"Current limited sale"),[ToolUtil judgeStringForDecimalPlaces:amount point:4]];
                    self.usedCount.text    = [NSString stringWithFormat:@"%@:%@ DWTT",LocalizationKey(@"Rushtobuy"),[ToolUtil judgeStringForDecimalPlaces:[NSString stringWithFormat:@"%@",self.flashSaleDic[@"flashsale_mount"]] point:4]];
                    CGFloat percent = [self.flashSaleDic[@"ratio"] floatValue];
                    self.percentLabel.text = [NSString stringWithFormat:@"%@%.2f%%",LocalizationKey(@"Current buying progress"),percent*100];
                    
                    CGRect rect = self.progressView.frame;
                    CGFloat width = SCREEN_WIDTH-64;
                    rect.size.width = width * percent;
                    self.progressView.frame = rect;
                
                    [self.headerView.qgbtn setImage:[UIImage imageNamed:@"qianggou_btn"] forState:UIControlStateNormal];
                }
                else if (currentTime < nextStarttime) {
                    if (_timer) {
                        dispatch_source_cancel(_timer);
                    }
                    _daojishi = nextStarttime - currentTime;
                    [self startTimer:_daojishi];
                    
                    self.headerView.qgTitle.text = LocalizationKey(@"Panic buying countdown");
                    self.canUsedCount.text = [NSString stringWithFormat:@"%@:%@ DWTT",LocalizationKey(@"Current limited sale"),[ToolUtil judgeStringForDecimalPlaces:[NSString stringWithFormat:@"%@",self.flashSaleDic[@"nextAmount"]] point:4]];
                    self.usedCount.text    = [NSString stringWithFormat:@"%@:0 DWTT",LocalizationKey(@"Rushtobuy")];
                    self.percentLabel.text = [NSString stringWithFormat:@"%@%@",LocalizationKey(@"Current buying progress"),@"0.00%"];
                    self.progressView.backgroundColor = [UIColor colorWithHEX:@"c5c5c5"];
                    
                    [self.headerView.qgbtn setImage:[UIImage imageNamed:@"qb_qianggou_end"] forState:UIControlStateNormal];
                }
                else {
                    if (_timer) {
                        dispatch_source_cancel(_timer);
                    }

                    self.headerView.qgTitle.text = LocalizationKey(@"Panic buying countdown");
                    self.headerView.secondTime.text = @"00";
                    self.headerView.miniteTime.text = @"00";
                    self.headerView.hourTime.text   = @"00";
                    self.progressView.backgroundColor = [UIColor colorWithHEX:@"c5c5c5"];

                    [self.headerView.qgbtn setImage:[UIImage imageNamed:@"qb_qianggou_end"] forState:UIControlStateNormal];
                }
                
            }
            else {
                [self.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }else{
            [self.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}
    
- (void)updateTime:(NSInteger)totals {
    
    if (totals <= 0) {
        _daojishi = 0;
        if (_timer) {
            dispatch_source_cancel(_timer);
        }
        [self Flashsale:nil];
    }
    NSInteger second = totals%60;
    self.headerView.secondTime.text = [NSString stringWithFormat:@"%02ld",second];
    
    NSInteger minite = (totals/60)%60;
    self.headerView.miniteTime.text = [NSString stringWithFormat:@"%02ld",minite];
    
    NSInteger hour   = totals/3600;
    self.headerView.hourTime.text = [NSString stringWithFormat:@"%02ld",hour];
}

-(void)rightButton {
    UIButton * issueButton = [UIButton buttonWithType:UIButtonTypeSystem];
    issueButton.frame = CGRectMake(0, 0, 80, 24);
    issueButton.titleLabel.font = [UIFont systemFontOfSize:12];
    
    [issueButton setTitle:LocalizationKey(@"Panic buying record") forState:UIControlStateNormal];
    issueButton.titleEdgeInsets = UIEdgeInsetsMake(0, 15, 0, -15);
    [issueButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [issueButton addTarget:self action:@selector(RighttouchEvent) forControlEvents:UIControlEventTouchUpInside];
    self.issueButton = issueButton;
    //添加到导航条
    UIBarButtonItem *leftBarButtomItem = [[UIBarButtonItem alloc]initWithCustomView:issueButton];
    self.navigationItem.rightBarButtonItem = leftBarButtomItem;
}

- (void)ViewTitleStr:(NSString *)titleStr contentStr:(NSString *)contentStr sureTag:(NSInteger)sureTag{
    
    self.alertView = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH-308)/2.0, (SCREEN_HEIGHT-200)/2.0, 308, 200)];
    [self.view addSubview:self.alertView];
    self.alertView.backgroundColor = [UIColor whiteColor];
    self.alertView.layer.masksToBounds = YES;
    self.alertView.layer.cornerRadius = 10;
    
    UIButton *cancelBtn = buttonTypeSystem;
    [self.alertView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(15);
        make.right.equalTo(-15);
    }];
    [cancelBtn setImage:ImageRenderingName(@"loginClose") forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnAct) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *titleLB = [[UILabel alloc]init];
    [self.alertView addSubview:titleLB];
    titleLB.textColor = kColor(maincolor);
    titleLB.font = kFont(18);
    titleLB.text = titleStr;
    [titleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(30);
        make.centerX.equalTo(0);
    }];
    
    UIButton *sureBtn = [[UIButton alloc]initWithFrame:CGRectMake(24, self.alertView.frame.size.height-50, self.alertView.frame.size.width-48, 34)];
    [self.alertView addSubview:sureBtn];
    [sureBtn setTitle:LocalizationKey(@"Confirm") forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = kFont(12);
    sureBtn.layer.masksToBounds = YES;
    sureBtn.layer.cornerRadius = 4;
    sureBtn.tag = sureTag;
    sureBtn.backgroundColor = tMainColor;
//    [ToolUtil view:sureBtn gradineViewOne:sureBtn.bounds colorOne:[UIColor colorWithHEX:maincolor] colorTwo:[UIColor colorWithHEX:mainGradientColor]];
    [sureBtn addTarget:self action:@selector(sureBtnAct:) forControlEvents:UIControlEventTouchUpInside];

    
    UILabel *contentLB = [[UILabel alloc]initWithFrame:CGRectMake(25, 72, self.alertView.frame.size.width-50, 40)];
    [self.alertView addSubview:contentLB];
    contentLB.font = kFont(12);
    contentLB.textColor = kColor(@"#333333");
    contentLB.numberOfLines = 0;
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:contentStr];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 12.0; // 设置行间距
    paragraphStyle.alignment = NSTextAlignmentJustified; //设置两端对齐显示
    [attributedStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attributedStr.length)];
    contentLB.attributedText = attributedStr;
    
    NSDictionary *attributes = @{NSFontAttributeName: contentLB.font, NSParagraphStyleAttributeName: paragraphStyle};
    CGSize contentSize = [contentLB.text boundingRectWithSize:CGSizeMake(contentLB.frame.size.width, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading) attributes:attributes context:nil].size;
    contentLB.frame = CGRectMake(25, 72, self.alertView.frame.size.width-50, contentSize.height);

    self.alertView.frame = CGRectMake((SCREEN_WIDTH-308)/2.0, (SCREEN_HEIGHT-150-contentLB.frame.size.height)/2.0-(150+contentLB.frame.size.height)/2.0, 308, 150+contentLB.frame.size.height);
    sureBtn.frame = CGRectMake(24, self.alertView.frame.size.height-50, self.alertView.frame.size.width-48, 34);

}

- (void)cancelBtnAct{
    self.alertView.hidden = YES;
    self.alertView = nil;
}

- (void)sureBtnAct:(UIButton *)sender{
    if (sender.tag == 100) {
        
        [self cancelBtnAct];
    }
    else if (sender.tag == 200) {
        
        [self cancelBtnAct];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    NSLog(@"didReceiveMemoryWarning");
}

@end
